package com.jk.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jk.dao.ProInfoDao;
import com.jk.dao.ProductDao;
import com.jk.dao.ProductesDao;
import com.jk.dao.SecKillDao;
import com.jk.entity.*;
import com.jk.service.ProductService;
import com.jk.utils.MsgUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Primary;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@SuppressWarnings("all")
@Primary
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductDao productDao;

    @Autowired
    private ProductesDao productesDao;

    @Autowired
    private ElasticsearchRestTemplate es;

    @Autowired
    private ProInfoDao proInfoDao;

//    @Autowired
//    private MongoTemplate mongoTemplate;


    @Override
    public Map getTypeList(ProductTypeEntity productTypeEntity) {
        QueryWrapper<ProductTypeEntity> wrapper = new QueryWrapper<>();
        try {
            if (productTypeEntity.getTypeName()!=null && productTypeEntity.getTypeName()!=""){
                wrapper.like("typeName",productTypeEntity.getTypeName());
            }
            List<ProductTypeEntity> productTypeEntities = productDao.selectList(wrapper);

            Map map = MsgUtil.returnMsg(200, "成功", productTypeEntities);

            return  map;
        }catch (Exception e){
           e.printStackTrace();
           return MsgUtil.returnMsg(500,"异常",null);
        }

    }
    //删除类型
    @Override
    public Map deleteType(Integer id) {
        try {
            productDao.deleteById(id);
            return MsgUtil.returnMsg(250,"成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return MsgUtil.returnMsg(500,"异常",null);
        }
    }
    //新增产品类型
    @Override
    public Map addType(ProductTypeEntity type) {
        productDao.insert(type);
        return MsgUtil.returnMsg(250,"成功",null);
    }
    //回显
    @Override
    public Map getTypeById(Integer id) {
        ProductTypeEntity productTypeEntity = productDao.selectById(id);
        return MsgUtil.returnMsg(250,"成功",productTypeEntity);
    }

    //编辑服务信息
    @Override
    public Map updateProType(ProductTypeEntity type) {
        UpdateWrapper<ProductTypeEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",type.getId());
        productDao.update(type,wrapper);
        return MsgUtil.returnMsg(250,"成功",null);
    }

    //查看产品信息
    @Override
    public Map getProList(ProductEntity product) {
        List<ProductEntity> proList = productDao.findProList(product);
        return MsgUtil.returnMsg(250,"成功",proList);
    }




    @Override
    public Map addPro(ProductEntity product) {
        product.setGoods_state("false");
        product.setDefinite(product.getProducts());
        proInfoDao.insert(product);

        return MsgUtil.returnMsg(250,"成功",null);
    }
    //删除
    @Override
    public Map deletePro(Integer id) {
        proInfoDao.deleteById(id);
        return MsgUtil.returnMsg(250,"成功",null);
    }

    @Override
    public Map getTProById(Integer id) {
        ProductEntity productEntity = proInfoDao.selectById(id);
        return MsgUtil.returnMsg(250,"成功",productEntity);
    }
    //修改产品信息
    @Override
    public Map updatePro(ProductEntity product) {
        QueryWrapper<ProductEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",product.getId());
        proInfoDao.update(product,wrapper);
        return MsgUtil.returnMsg(250,"成功",null);
    }

    @Resource
    private MongoTemplate mongoTemplate;
    //进货
    @Override
    public Map add(PurRecord purRecord) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        purRecord.setPurDate(sdf.format(new Date()));
        purRecord.setTotalPrice(purRecord.getPrice()*purRecord.getInCount());
        mongoTemplate.save(purRecord);
        UpdateWrapper<ProductEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",purRecord.getProNum());
        wrapper.set("surplusCount",purRecord.getSurpluscount()+purRecord.getInCount());
        proInfoDao.update(null,wrapper);
        return null;
    }

    @Override
    public Map getNote(PurRecord purRecord) {
        Query query = new Query();

        List<PurRecord> purRecords = mongoTemplate.find(query, PurRecord.class);
        return MsgUtil.returnMsg(200,"ok",purRecords);
    }

    @Override
    public List<ProductEntity> getcount(ProductEntity product) {
        return productDao.getcount(product);
    }

    @Override
    public List<ProductEntity> getallget(ProductEntity product) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /**
         * 模糊差
         */
        if(product.getDefinite()!=null && product.getDefinite()!=""){
            boolQueryBuilder.must(QueryBuilders.matchQuery("definite",product.getDefinite()));//商品模糊查
        }
//        if(sig.getState()!=null && sig.getState()!= -1){//签约状态查询
//            boolQueryBuilder.must(QueryBuilders.termQuery("state",sig.getState()));
//        }

        /**
         * 是否货到付款
         */
        if (product.getProductprice() !=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("productprice",product.getProductprice()));
        }
        /**
         * 价格区间查
         */
        if (product.getMaxPrice() !=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").lte(product.getMaxPrice()));
        }
        if (product.getMinPrice() !=null){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("price").gte(product.getMinPrice() ));
        }





        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                //高亮设置
                .withHighlightFields(new HighlightBuilder.Field("proname").preTags("<em>").postTags("</em>"))
                .build();
        SearchHits<ProductEntity> hits = es.search(query, ProductEntity.class);
        List<ProductEntity> list=new ArrayList<>();//new 一个空的list、
        //所有的值都在hits中，循环可以得到数据
        hits.forEach(hit->{
            ProductEntity content = hit.getContent();//原字段
            Map<String, List<String>> highlightFields = hit.getHighlightFields();//高亮后的字段
            //3木运算符，如果没有高亮的时候，不会替换原字段

            hit.getContent().setProname(highlightFields.get("proname")  == null ? hit.getContent().getProname():highlightFields.get("proname").get(0).toString());
            list.add(content);
            System.out.println(list);
        });
        return list;
    }

    @Override
    public List<ProductEntity> getByid(ProductEntity product) {
        NativeSearchQuery query=new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("id",product.getId()))
                .build();
        SearchHits<ProductEntity> search = es.search(query, ProductEntity.class);
        List<ProductEntity> list=new ArrayList<>();//new 一个空的list、
        search.forEach(sea->{
            ProductEntity content = sea.getContent();
            list.add(content);
        });
        return list;
    }



    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void getredis(Integer id,Integer buycount,Integer userId) {

        NativeSearchQuery query=new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("id",id))
                .build();
        SearchHits<ProductEntity> search = es.search(query, ProductEntity.class);

        search.forEach(sea->{
            ProductEntity content = sea.getContent();
            System.out.println(content);

            Boolean aBoolean = redisTemplate.opsForHash().hasKey(userId+"", id);
            if (aBoolean){
                ProductEntity count= (ProductEntity) redisTemplate.opsForHash().get(userId+"", id);
                content.setBuycount(count.getBuycount()+buycount);
                redisTemplate.opsForHash().put(userId+"",id,content);
            }else{
                content.setBuycount(buycount);
                redisTemplate.opsForHash().put(userId+"",id,content);

            }
        });

    }

    //取redis
    @Override
    public List<ProductEntity> getquredis(Integer userId) {
        List values = redisTemplate.opsForHash().values(userId+"");
        System.out.println(values);
        return values;
    }

    @Override
    public void deletee(Integer id,Integer userId) {
        redisTemplate.opsForHash().delete(userId+"",id);
    }

    @Override
    public List<ProductEntity> pruduceFindAll(ProductEntity productEntity) {
        Wrapper<ProductEntity> wapper = new QueryWrapper<>();
        List<ProductEntity> list = proInfoDao.selectList(wapper);
        return list;
    }

    @Override
    public ProductEntity pruduceid(Integer id) {
        ProductEntity productEntity = proInfoDao.selectById(id);
        return productEntity;
    }

    //查看排行榜
    @Override
    public List<ProductEntity> getPaihang(ProductEntity productEntity) {
        NativeSearchQuery query=new NativeSearchQueryBuilder()
                .withSort(SortBuilders.fieldSort("productcount").order(SortOrder.DESC)) //排序
                .build();
        SearchHits<ProductEntity> search = es.search(query, ProductEntity.class);
        List<ProductEntity> list=new ArrayList<>();//new 一个空的list、
        search.forEach(sea->{
            ProductEntity content = sea.getContent();
            list.add(content);
        });
        return list;
    }

    @Autowired
    private SecKillDao secKillDao;
    @Override
    public Map getKillById(Integer id) {
        SecondKillEntity kill = secKillDao.selectById(id);
        return MsgUtil.returnMsg(200,"ok",kill);
    }

    @Override
    public void updateKill(SecondKillEntity secondKill) {
        secKillDao.updateById(secondKill);
    }

    @Override
    public void modo(Integer id, Integer userId, Integer buycount) {
        OrderEntity orderEntity = new OrderEntity();
        ProductEntity productEntity = proInfoDao.selectById(id);
        orderEntity.setBuycount(buycount);
        orderEntity.setOrderType(2);
        orderEntity.setPrice(productEntity.getPrice());
        orderEntity.setProname(productEntity.getProname());
        orderEntity.setProimg(productEntity.getProimg());
        orderEntity.setProducts(productEntity.getProducts());
        orderEntity.setDefinite(productEntity.getDefinite());
        orderEntity.setBrand(productEntity.getBrand());
        orderEntity.setIds(productEntity.getIds());
        orderEntity.setBuyDate(String.valueOf(new Date()));
        mongoTemplate.save(orderEntity);
    }



}
